<!--  -->
<template>
  <div class="Write">
    <div class="pc-container">
      <el-form ref="form" :model="form" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文章标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入文章标题"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="分类">
              <el-select v-model="form.categoryId" placeholder="请选择">
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select v-model="form.tags" placeholder="请选择" multiple>
                <el-option
                  v-for="tag in tagList"
                  :key="tag.id"
                  :label="tag.name"
                  :value="tag.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文章摘要">
              <el-input v-model="form.summary" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" />

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="缩略图">
              <el-upload
                :file-list="fileList"
                class="upload-demo"
                list-type="picture"
                drag
                name="img"
                action="upload"
                :on-remove="fileRemove"
                :limit="1"
                :http-request="handleUpload"
                :on-exceed="onExceed"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" size="medium" @click="handleSubmit">{{
                aId ? "更新" : "发送审核"
              }}</el-button>
            </el-form-item>
            <el-form-item>
              <el-button v-if="!aId" type="info" @click="handleSave"
                >保存到草稿箱</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <mavon-editor ref="md" v-model="form.content" @imgAdd="addImg" />
        </el-row>
      </el-form>
    </div>
    <!-- 移动端的排版 -->
    <div class="app-container">
      <el-form ref="form" :model="form" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="文章标题" prop="title">
              <el-input
                v-model="form.title"
                placeholder="请输入文章标题"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="分类">
              <el-select v-model="form.categoryId" placeholder="请选择">
                <el-option
                  v-for="category in categoryList"
                  :key="category.id"
                  :label="category.name"
                  :value="category.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="标签">
              <el-select v-model="form.tags" placeholder="请选择" multiple>
                <el-option
                  v-for="tag in tagList"
                  :key="tag.id"
                  :label="tag.name"
                  :value="tag.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="文章摘要">
              <el-input v-model="form.summary" type="textarea" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="缩略图">
              <el-upload
                :file-list="fileList"
                class="upload-demo"
                list-type="picture"
                drag
                name="img"
                action="upload"
                :on-remove="fileRemove"
                :limit="1"
                :http-request="handleUpload"
                :on-exceed="onExceed"
              >
                <i class="el-icon-upload" />
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过500kb
                </div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item>
              <el-button type="primary" size="medium" @click="handleSubmit">
                {{ aId ? "更新" : "发送审核" }}
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item>
              <el-button v-if="!aId" type="info" @click="handleSave">
                保存到草稿箱
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <mavon-editor ref="md" v-model="form.content" @imgAdd="addImg" />
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import { bloguploadImg } from "@/api/blogupload";
import { addArticle, getArticle, updateArticle } from "@/api/article";
import { listAllTag } from "@/api/article";
import { listAllCategory } from "../api/category";
import { getToken } from "../utils/auth.js";
export default {
  data() {
    return {
      form: {
        title: "",
        thumbnail: "",
        isTop: "1",
        isComment: "0",
        content: "",
      },
      categoryList: [],
      tagList: [],
      aId: -1,
      fileList: [],
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.aId = route.query && route.query.id;
        // console.log(this.aId);
      },
      immediate: true,
    },
  },

  components: {
    //定义组件
  },
  created() {
    //生命周期函数
  },
  methods: {
    getArticle() {
      getArticle(this.aId).then((response) => {
        this.form = response;
        this.fileList.push({ name: "缩略图", url: response.thumbnail });
      });
    },
    handleSave() {
      var that = this;
      var tokenInfo = getToken();

      if (!tokenInfo || Date.now() > tokenInfo.expirationTime) {
        that
          .$confirm(
            "登录状态已过期或者未登录，您需要重新登录后才能评论，是否前往登录页面?",
            "提示",
            {
              confirmButtonText: "确定前往",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
          .then(() => {
            //确定，跳转至登录页面
            //储存当前页面路径，登录成功后跳回来
            localStorage.setItem("logUrl", that.$route.fullPath);
            that.$router.push({ path: "/About" });
          })
          .catch(() => {});
        return;
      }
      // 验证表单是否填写完整
      if (!this.validateForm()) {
        return;
      }
      // 弹出确认对话框，询问是否保存草稿
      this.$confirm("是否保存为草稿？", "提示", {
        confirmButtonText: "保存",
        cancelButtonText: "取消",
        type: "info",
      })
        .then(() => {
          // 用户点击了保存
          // 执行保存草稿的逻辑
          // 这里你可以调用保存草稿的接口或者执行其他操作

          // 模拟保存成功，实际应该根据接口返回结果判断是否保存成功

          this.form.status = "1";
          addArticle(this.form).then((response) => {
            this.$message.success("保存成功");
          });

          // 刷新当前页面，你可以根据实际情况选择刷新页面的方式
          location.reload(); // 或者使用 this.$router.push({ path: '/' }) 来跳转到当前页面
        })
        .catch(() => {
          // 用户点击了取消，不执行任何操作
        });
    },

    validateForm() {
      // 判断文章标题是否为空
      if (!this.form.title) {
        this.$message.error("请输入文章标题");
        return false;
      }

      // 判断分类是否选择
      if (!this.form.categoryId) {
        this.$message.error("请选择分类");
        return false;
      }

      // 判断标签是否选择
      if (this.form.tags.length === 0) {
        this.$message.error("请选择标签");
        return false;
      }

      return true;
    },

    //发送博客
    handleSubmit() {
      var that = this;
      var tokenInfo = getToken();

      if (!tokenInfo || Date.now() > tokenInfo.expirationTime) {
        that
          .$confirm(
            "登录状态已过期或者未登录，您需要重新登录后才能评论，是否前往登录页面?",
            "提示",
            {
              confirmButtonText: "确定前往",
              cancelButtonText: "取消",
              type: "warning",
            }
          )
          .then(() => {
            //确定，跳转至登录页面
            //储存当前页面路径，登录成功后跳回来
            localStorage.setItem("logUrl", that.$route.fullPath);
            that.$router.push({ path: "/About" });
          })
          .catch(() => {});
        return;
      }
      // 验证表单是否填写完整
      if (!this.validateForm()) {
        return;
      }

      const operation = this.aId ? "更新" : "发送博文给管理员审核";

      // 弹出确认提示框
      this.$confirm(`是否确认${operation}博客？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击了确认按钮，执行发布或更新博客的逻辑
          if (!this.aId) {
            // 新增博客逻辑
            this.form.status = "0";
            addArticle(this.form).then((response) => {
              this.$message.success(`博客${operation}成功,积分扣除1000`);
              setTimeout(() => {
                location.reload(); // 或者使用 this.$router.push({ path: '/' }) 来跳转到当前页面
              }, 1000);
              this.$router.push({ path: "/Write" });
            });
          } else {
            // 更新博客逻辑
            updateArticle(this.form).then((response) => {
              this.$message.success(`博客${operation}成功,积分扣除1000`);
              setTimeout(() => {
                location.reload(); // 或者使用 this.$router.push({ path: '/' }) 来跳转到当前页面
              }, 1000);
              this.$router.push({ path: "/Write" });
            });
          }
        })
        .catch(() => {
          // 用户点击了取消按钮或者关闭了提示框，不执行任何操作
        });
    },
    validateForm() {
      // 判断文章标题是否为空
      if (!this.form.title) {
        this.$message.error("请输入文章标题");
        return false;
      }

      // 判断分类是否选择
      if (!this.form.categoryId) {
        this.$message.error("请选择分类");
        return false;
      }

      // 判断标签是否选择
      if (this.form.tags.length === 0) {
        this.$message.error("请选择标签");
        return false;
      }

      return true;
    },
    onExceed() {
      this.$message.error("只能上传一个图片");
    },
    handleUpload(img) {
      bloguploadImg(img.file)
        .then((response) => {
          this.form.thumbnail = response;
          this.fileList.push({ name: img.file.name, url: response });
        })
        .catch((error) => {
          this.$message.error(error.msg);
        });
    },
    fileRemove(file, fileList) {
      this.fileList.pop();
    },
    // 绑定@imgAdd event
    addImg(pos, file) {
      // 第一步.将图片上传到服务器.
      bloguploadImg(file)
        .then((response) => {
          this.$refs.md.$img2Url(pos, response);
        })
        .catch((error) => {
          this.$message.error(error.msg);
        });
    },
    getCategoryAndTag() {
      listAllCategory()
        .then((response) => {
          this.categoryList = response;
        })
        .catch((error) => {
          console.error("获取分类列表时出错", error);
        });

      listAllTag()
        .then((response) => {
          this.tagList = response;
          //console.log(response);
        })
        .catch((error) => {
          console.error("获取标签列表时出错", error);
        });
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
  },
  created() {
    this.getCategoryAndTag();
    if (this.aId) {
      this.getArticle();
    }
  },
};
</script>


<style>

@media (max-width: 767px) {
  .pc-container {
    display: none;
  }
  .el-upload-dragger{
    width: 290px;
  }
}
@media (min-width: 768px) {
  .app-container {
    display: none;
  }
}
.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.el-col .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;

  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
